<?php

namespace App\Http\Controllers\AdminShop;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use DB;

class TypeController extends Controller
{
    /**
     * 商品分类添加
     */
    public function getAdd()
    {
        return view('adminShop.type.add');
    }

    /**
     * 商品分类添加
     */
    public function postInsert(Request $request)
    {
        // 添加商品分类表单数据验证
        $this->validate($request,[
            'typename' => 'required',
        ],[
            'typename.required' => '必填',
        ]);

        $data = $request->except('_token');

        if(DB::table('shoptypes')->insert($data)) {
            return redirect('/type/list')->with('info','数据插入成功');
        }else{
            return back()->with('info','数据插入失败');
        }
    }

    /**
     * 商品分类列表
     */
    public function getList(Request $request)
    {
        $data = DB::table('shoptypes')
            ->where(function($query)use($request) {
                $keyword = $request->input('keyword');
                if(!empty($keyword)) {
                    $query->where('typename','like','%'.$keyword.'%');
                }
            })
            ->where('sid','=',session('pid'))
            ->paginate(5);
        return view('adminShop.type.list',[
            'data'=>$data,
            'request'=>$request,
        ]);
    }

    /**
     * 修改商品分类名称
     */
    public function getEdit(Request $request)
    {
        $info = DB::table('shoptypes')->where('id','=',$request->input('id'))->first();
        return view('adminShop.type.edit',[
            'info' => $info
        ]);
    }

    /**
     * 商品分类更新
     */
    public function postUpdate(Request $request)
    {
        $this->validate($request,[
            'typename' => 'required',
        ],[
            'typename.required' => '必填',
        ]);

        $data = $request->except('_token');
        // 开始更新
        $res = DB::table('shoptypes')->where('id','=',$request->input('id'))->update($data);

        if($res) {
            return redirect('/type/list')->with('ifno','更新成功');
        }else{
            return back()->with('info','更新失败');
        }
    }

    /**
     * 商品分类删除
     */
    public function getDelete(Request $request)
    {
        $res = DB::table('shoptypes')->where('id','=',$request->input('id'))->delete();

        if($res) {
            return back()->with('info','删除成功');
        }else{
            return back()->with('info','删除失败'); 
        }
    }
}
